import os
import xlrd   
from openpyxl import Workbook, load_workbook    
import traceback 
import re                         
def is_number(s):
    if type(s) == str:
        if len(s) > 1 and s[0] == "0":
            return False
    try:
        int(s)
        return True
    except ValueError:
        pass

    try:
        float(s)
        return True
    except ValueError:
        pass

    return False
def is_chinese(text):
    # 使用正则表达式匹配中文字符
    pattern = re.compile(r'[\u4e00-\u9fa5]')
    if pattern.search(text):
        return True
    else:
        return False
def removenilvelue(data):
    if data[-1] == "":
        data.pop()

#拿到配置key
def getKeyData(csvdata):
    key1, key2, Key = None, None, None
    for x in csvdata:
        if "///key" in x[0]:
            Key = x
            key1 ,key2 = x[1], x[2]
            break

    #拿到字段数据
    Index, Filter = None, None
    for x in csvdata:
        if "/" == x[0][:1]:
            if key1 in x[0]:
                Index = x
            elif key2 in x[0]:
                Filter = x

    isarr = "[]" in Index[0]
    if isarr:
        Index[0] = Key[1]

    # print(Index)
    # print(Filter)
    # print(key1)
    return Index, Filter, key1
def reverse_string(s):
    return s[:1]


 #获取写入Lua文件的额数据
def getWriteLuaData(csvdata, Index, Filter, Key1):
    luatable_server = {}   #转服务器lua表数据
    luatable_client = {}
    notarr = "/" in Index[0]
    count = 1
    for x in csvdata:
        #过滤没用的数据
        if x[0][:1] == "/" or x[0][:1] == "," or x[0][:1] == "" or x[0] == Index[0]:
            continue

        data_server = {}
        data_client = {}
        for i,key in enumerate(Index):
            #print(i,key)

            if notarr and i == 0:
                continue

            try:
                if Filter[i] == '0' or Filter[i] == "" or Filter[i] == 0:
                    continue
            except TypeError:
                print(Filter)
            data = x[i]
            if data == "" or data == "\n":
                continue
            # print(data)
            if not is_number(data):
                isturn = False
                if "|" in data:
                    isturn = True
                    data = data.split("|")
                    removenilvelue(data)
                    for ii in range(len(data)):
                        if "^" in data[ii]:
                            data[ii] = data[ii].split("^")
                            removenilvelue(data[ii])
                elif "^" in data:
                    isturn = True
                    data = data.split("^")
                    removenilvelue(data)
                    data = [data]

                #数组转对象
                if isturn:
                    dataobj = {}
                    for sz in range(len(data)):
                        v = data[sz]
                        addi = sz + 1
                        if type(v) == list:
                            dataobj[addi] = {}
                            for ii in range(len(v)):
                                dataobj[addi][ii+1] = v[ii]
                        else:
                            dataobj[addi] = data[sz]
                    data = dataobj 
            if notarr==False and i ==0 :
                data_client[key] = data
                data_server[key] = data
            elif Filter[i] == '1' or Filter[i] == 1 :        
                data_server[key] = data
            elif Filter[i] == '2' or Filter[i] == 2 :
                data_client[key] = data
            elif Filter[i] == '3':
                data_client[key] = data
                data_server[key] = data
        # data_server[Key1] = x[0]
        luatable_server[x[0]] = data_server
        luatable_client[x[0]] = data_client
        # if notarr:
        #     luatable_server[x[0]] = data_server
        #     luatable_client[x[0]] = data_client
        # else:
        #     luatable_server[str(count)] = data_server
        #     luatable_client[str(count)] = data_client
        #     count = count + 1

    # print(luatable_server)
    return luatable_server,luatable_client


#递归写Lua文件
def writeLuaTable(value, f, deep, key):
    tab = ""
    for _ in range(deep):
        tab = tab + "\t"
    if type(value) == dict:
        if is_number(key):
            f.write("%s[%s] = {\n" % (tab, key))
        elif is_chinese(key):#or any(char.isdigit() for char in key)
            f.write("%s[\"%s\"] = {\n" % (tab, key))
        else:
            f.write("%s%s = {\n" % (tab, key))

        for k,v in value.items():
            writeLuaTable(v, f, deep+1, k)

        if deep == 0:
            f.write("%s}\n" % (tab))
        else:
            f.write("%s},\n" % (tab))
    else:
        if is_number(key):
            if is_number(value):
                f.write("%s[%s] = %s,\n" % (tab, key, value))
            # elif is_chinese(key):
            #     f.write("%s[\"%s\"] = {\n" % (tab, key))
            else:
                f.write("%s[%s] = \"%s\",\n" % (tab, key, value))
        else:
            if is_number(value):
                f.write("%s%s = %s,\n" % (tab, key, value))
            # elif is_chinese(key):
            #     f.write("%s[\"%s\"] = {\n" % (tab, key))
            else:
                f.write("%s%s = \"%s\",\n" % (tab, key, value))
def xlsxToList(file):
    wb = load_workbook(file, read_only=True)
    ws = wb.active
    csvdata = []
    for row in ws.iter_rows(values_only=True):
        data_row = []
        for cell in row:
            text =convert_to_str(cell)
            #print(text,type(text) )
            if text == 'None':
                text=""
            data_row.append(convert_to_str(text))

            #data_row.append(convert_to_str(cell))
        csvdata.append(data_row)
    wb.close()
    return csvdata

def xlsToList(file):
    xlsData = xlrd.open_workbook(file)
    sheet = xlsData.sheet_by_index(0)  # 通过索引获取第一个工作表
    csvdata = []
    for r in range(sheet.nrows):
        data_row = []
        for c in range(sheet.ncols):
            #print(sheet.cell_value(r, c),type(sheet.cell_value(r, c)))
            data_row.append(convert_to_str(sheet.cell_value(r, c)))
        csvdata.append(data_row)
    return csvdata

def csvToList(file):
    with open(file, "r") as f:
        csvdata = [line.strip().split(",") for line in f]
    return csvdata

def convert_to_str(cell_value):
    if isinstance(cell_value, float):  # 如果是浮点数类型
        return str(int(cell_value))    # 转换为整数后再转换为字符串
    return str(cell_value)             # 其他类型直接转换为字符串

def load_csvdata(file_path):
    if file_path.endswith(".csv"):
        return csvToList(file_path)
    elif file_path.endswith(".xlsx"):
        return xlsxToList(file_path)
    elif file_path.endswith(".xls"):
        return xlsToList(file_path)
    else:
        return None

def writeLuacsv(self, file, serverPath, clientPath, formPath):
    try:
        csvdata = load_csvdata(os.path.join(formPath, file))
        if csvdata is not None:
            turnLua(self, csvdata, file, serverPath, clientPath)
        else:
            self.text_tips.insert('0.0', f"【错误】不支持的文件类型：{file}\n")
    except Exception as e:
        self.text_tips.insert('0.0', f"【错误】转换文件失败：{file}，错误信息：{str(e)}\n")
        traceback.print_exc()
def turnLua(self, csvdata, file, serverPath, clientPath):
    Index, Filter, Key1 = getKeyData(csvdata)
    luatable_server, luatable_client = getWriteLuaData(csvdata, Index, Filter, Key1)
    filename = os.path.splitext(file)[0] + ".lua"
    
    # 写入服务器端文件
    write_lua_file(serverPath + filename, luatable_server, "gbk")
    self.text_tips.insert('0.0', "【服务端】转文件成功：" + file + '\n')
    
    # 写入客户端文件
    write_lua_file(clientPath + filename, luatable_client, "utf-8")
    self.text_tips.insert('0.0', "【客户端】转文件成功：" + file + '\n')

def write_lua_file(filepath, luatable, encoding):
    with open(filepath, "w", encoding=encoding) as f:
        writeLuaTable(luatable, f, 0, "local config")
        f.write("return config")

def filesCount(formPath):
    all_files = os.listdir(formPath)
    
    # 筛选出所有扩展名为 .csv、.xls 和 .xlsx 的文件
    filtered_files = [x for x in all_files if os.path.isfile(formPath+x) and os.path.splitext(x)[1] in ['.csv', '.xls', '.xlsx']]
    
    return filtered_files